#!/bin/sh
#
# FFmpeg configure script
#
# Copyright (c) 2000, 2001, 2002 Fabrice Bellard
# Copyright (c) 2005-2006 Diego Biurrun
# Copyright (c) 2005-2006 Mans Rullgard
#

# make sure we are running under a compatible shell
# try to make this part work with most shells

try_exec(){
    echo "Trying shell $1"
    type "$1" >/dev/null 2>&1 && exec "$@"
}

unset foo
(: ${foo%%bar}) 2>/dev/null
E1="$?"

(: ${foo?}) 2>/dev/null
E2="$?"

if test "$E1" != 0 || test "$E2" = 0; then
    echo "Broken shell detected.  Trying alternatives."
    export FF_CONF_EXEC
    if test "0$FF_CONF_EXEC" -lt 1; then
        FF_CONF_EXEC=1
        try_exec bash "$0" "$@"
    fi
    if test "0$FF_CONF_EXEC" -lt 2; then
        FF_CONF_EXEC=2
        try_exec ksh "$0" "$@"
    fi
    if test "0$FF_CONF_EXEC" -lt 3; then
        FF_CONF_EXEC=3
        try_exec /usr/xpg4/bin/sh "$0" "$@"
    fi
    echo "No compatible shell script interpreter found."
    echo "This configure script requires a POSIX-compatible shell"
    echo "such as bash or ksh."
    echo "THIS IS NOT A BUG IN FFMPEG, DO NOT REPORT IT AS SUCH."
    echo "Instead, install a working POSIX-compatible shell."
    echo "Disabling this configure test will create a broken FFmpeg."
    if test "$BASH_VERSION" = '2.04.0(1)-release'; then
        echo "This bash version ($BASH_VERSION) is broken on your platform."
        echo "Upgrade to a later version if available."
    fi
    exit 1
fi

show_help(){
  echo "Usage: configure [options]"
  echo "Options: [defaults in brackets after descriptions]"
  echo
  echo "Standard options:"
  echo "  --help                   print this message"
  echo "  --log[=FILE|yes|no]      log tests and output to FILE [config.err]"
  echo "  --prefix=PREFIX          install in PREFIX [$PREFIX]"
  echo "  --libdir=DIR             install libs in DIR [PREFIX/lib]"
  echo "  --shlibdir=DIR           install shared libs in DIR [PREFIX/lib]"
  echo "  --incdir=DIR             install includes in DIR [PREFIX/include/ffmpeg]"
  echo "  --mandir=DIR             install man page in DIR [PREFIX/share/man]"
  echo "  --enable-static          build static libraries [default=yes]"
  echo "  --disable-static         do not build static libraries [default=no]"
  echo "  --enable-shared          build shared libraries [default=no]"
  echo "  --disable-shared         do not build shared libraries [default=yes]"
  echo "  --enable-gpl             allow use of GPL code, the resulting libav*"
  echo "                           and ffmpeg will be under GPL [default=no]"
  echo "  --enable-pp              enable GPLed postprocessing support [default=no]"
  echo "  --enable-swscaler        software scaler support [default=no]"
  echo "  --enable-beosthreads     use BeOS threads [default=no]"
  echo "  --enable-pthreads        use pthreads [default=no]"
  echo "  --enable-w32threads      use Win32 threads [default=no]"
  echo "  --enable-x11grab         enable X11 grabbing [default=no]"
  echo
  echo "External library support:"
  echo "  --enable-sunmlib         use Sun medialib [default=no]"
  echo "  --enable-liba52          enable GPLed liba52 support [default=no]"
  echo "  --enable-liba52bin       open liba52.so.0 at runtime [default=no]"
  echo "  --enable-avisynth        allow reading AVISynth script files [default=no]"
  echo "  --enable-libamr-nb       enable libamr-nb floating point audio codec"
  echo "  --enable-libamr-wb       enable libamr-wb floating point audio codec"
  echo "  --enable-libdc1394       enable IIDC-1394 grabbing using libdc1394"
  echo "                           and libraw1394 [default=no]"
  echo "  --enable-libfaac         enable FAAC support via libfaac [default=no]"
  echo "  --enable-libfaad         enable FAAD support via libfaad [default=no]"
  echo "  --enable-libfaadbin      open libfaad.so.0 at runtime [default=no]"
  echo "  --enable-libgsm          enable GSM support via libgsm [default=no]"
  echo "  --enable-libmp3lame      enable MP3 encoding via libmp3lame [default=no]"
  echo "  --enable-libnut          enable NUT (de)muxing via libnut,"
  echo "                           native demuxer exists [default=no]"
  echo "  --enable-libogg          enable Ogg muxing via libogg [default=no]"
  echo "  --enable-libtheora       enable Theora encoding via libtheora [default=no]"
  echo "  --enable-libvorbis       enable Vorbis en/decoding via libvorbis,"
  echo "                           native implementations exist [default=no]"
  echo "  --enable-libx264         enable H.264 encoding via x264 [default=no]"
  echo "  --enable-libxvid         enable Xvid encoding via xvidcore,"
  echo "                           native MPEG-4/Xvid encoder exists [default=no]"
  echo ""
  echo "Advanced options (experts only):"
  echo "  --source-path=PATH       path to source code [$source_path]"
  echo "  --cross-prefix=PREFIX    use PREFIX for compilation tools [$cross_prefix]"
  echo "  --cross-compile          assume a cross-compiler is used"
  echo "  --target-os=OS           compiler targets OS [$targetos]"
  echo "  --cc=CC                  use C compiler CC [$cc]"
  echo "  --make=MAKE              use specified make [$make]"
  echo "  --extra-cflags=ECFLAGS   add ECFLAGS to CFLAGS [$CFLAGS]"
  echo "  --extra-ldflags=ELDFLAGS add ELDFLAGS to LDFLAGS [$LDFLAGS]"
  echo "  --extra-libs=ELIBS       add ELIBS [$ELIBS]"
  echo "  --build-suffix=SUFFIX    suffix for application specific build []"
  echo "  --arch=ARCH              select architecture  [$arch]"
  echo "  --cpu=CPU                selects the minimum cpu required (affects"
  echo "                           instruction selection, may crash on older CPUs)"
  echo "  --enable-powerpc-perf    enable performance report on PPC"
  echo "                           (requires enabling PMC)"
  echo "  --disable-mmx            disable MMX usage"
  echo "  --disable-armv5te        disable armv5te usage"
  echo "  --disable-armv6          disable armv6 usage"
  echo "  --disable-iwmmxt         disable iwmmxt usage"
  echo "  --disable-altivec        disable AltiVec usage"
  echo "  --disable-network        disable network support [default=no]"
  echo "  --disable-ipv6           disable ipv6 support [default=no]"
  echo "  --disable-zlib           disable zlib [default=no]"
  echo "  --disable-vhook          disable video hooking support"
  echo "  --disable-debug          disable debugging symbols"
  echo "  --disable-mpegaudio-hp   faster (but less accurate)"
  echo "                           MPEG audio decoding [default=no]"
  echo "  --enable-gray            enable full grayscale support (slower color)"
  echo "  --disable-ffmpeg         disable ffmpeg build"
  echo "  --disable-ffserver       disable ffserver build"
  echo "  --disable-ffplay         disable ffplay build"
  echo "  --enable-small           optimize for size instead of speed"
  echo "  --enable-memalign-hack   emulate memalign, interferes with memory debuggers"
  echo "  --disable-encoder=NAME   disables encoder NAME"
  echo "  --enable-encoder=NAME    enables encoder NAME"
  echo "  --disable-decoder=NAME   disables decoder NAME"
  echo "  --enable-decoder=NAME    enables decoder NAME"
  echo "  --disable-encoders       disables all encoders"
  echo "  --disable-decoders       disables all decoders"
  echo "  --disable-muxer=NAME     disables muxer NAME"
  echo "  --enable-muxer=NAME      enables muxer NAME"
  echo "  --disable-muxers         disables all muxers"
  echo "  --disable-demuxer=NAME   disables demuxer NAME"
  echo "  --enable-demuxer=NAME    enables demuxer NAME"
  echo "  --disable-demuxers       disables all demuxers"
  echo "  --enable-parser=NAME     enables parser NAME"
  echo "  --disable-parser=NAME    disables parser NAME"
  echo "  --disable-parsers        disables all parsers"
  echo "  --enable-bsf=NAME        enables bitstream filter NAME"
  echo "  --disable-bsf=NAME       disables bitstream filter NAME"
  echo "  --disable-bsfs           disables all bitstream filters"
  echo "  --enable-protocol=NAME   enables protocol NAME"
  echo "  --disable-protocol=NAME  disables protocol NAME"
  echo "  --disable-protocols      disables all protocols"
  echo "  --list-decoders          show all available decoders"
  echo "  --list-encoders          show all available encoders"
  echo "  --list-muxers            show all available muxers"
  echo "  --list-demuxers          show all available demuxers"
  echo "  --list-parsers           show all available parsers"
  echo "  --list-protocols         show all available protocols"
  echo "  --list-bsfs              show all available bitstream filters"
  echo
  echo "Developer options (useful when working on FFmpeg itself):"
  echo "  --enable-gprof           enable profiling with gprof [$gprof]"
  echo "  --disable-opts           disable compiler optimizations"
  echo "  --enable-extra-warnings  enable more compiler warnings"
  echo "  --disable-strip          disable stripping of executables and shared libraries"
  echo ""
  echo "NOTE: Object files are built at the place where configure is launched."
  exit 1
}

log(){
    echo "$@" >>$logfile
}

log_file(){
    log BEGIN $1
    cat -n $1 >>$logfile
    log END $1
}

echolog(){
    log "$@"
    echo "$@"
}

die(){
    echolog "$@"
    cat <<EOF
If you think configure made a mistake, make sure you are using the latest
version from SVN.  If the latest version fails, report the problem to the
ffmpeg-devel@mplayerhq.hu mailing list or IRC #ffmpeg on irc.freenode.net.
EOF
    if enabled logging; then
        cat <<EOF
Include the log file "$logfile" produced by configure as this will help
solving the problem.
EOF
    else
cat <<EOF
Rerun configure with logging enabled (do not use --log=no), and include the
log this produces with your report.
EOF
    fi
    rm -f $TMPC $TMPO $TMPE $TMPS $TMPH
    exit 1
}

# "tr '[a-z]' '[A-Z]'" is a workaround for Solaris tr not grokking "tr a-z A-Z"
toupper(){
    echo "$@" | tr '[a-z]' '[A-Z]'
}

tolower(){
    echo "$@" | tr '[A-Z]' '[a-z]'
}

set_all(){
    value=$1
    shift
    for var in $*; do
        eval $var=$value
    done
}

pushvar(){
    for var in $*; do
        eval level=\${${var}_level:=0}
        eval ${var}_${level}="\$$var"
        eval ${var}_level=$(($level+1))
    done
}

popvar(){
    for var in $*; do
        eval level=\${${var}_level:-0}
        test $level = 0 && continue
        eval level=$(($level-1))
        eval $var="\${${var}_${level}}"
        eval ${var}_level=$level
        eval unset ${var}_${level}
    done
}

enable(){
    set_all yes $*
}

disable(){
    set_all no $*
}

enabled(){
    eval test "x\$$1" = "xyes"
}

disabled(){
    eval test "x\$$1" = "xno"
}

enabled_all(){
    for opt; do
        enabled $opt || return 1
    done
}

disabled_all(){
    for opt; do
        disabled $opt || return 1
    done
}

enabled_any(){
    for opt; do
        enabled $opt && return 0
    done
}

disabled_any(){
    for opt; do
        disabled $opt && return 0
    done
}

is_in(){
    value=$1
    shift
    for var in $*; do
        [ $var = $value ] && return 0
    done
    return 1
}

check_deps(){
    for cfg; do
        enabled ${cfg}_checking && die "Circular dependency for $cfg."
        disabled ${cfg}_checking && continue
        enable ${cfg}_checking

        eval dep_all="\$${cfg}_deps"
        eval dep_any="\$${cfg}_deps_any"

        pushvar cfg dep_all dep_any
        check_deps $dep_all $dep_any
        popvar cfg dep_all dep_any

        enabled_all $dep_all || disable $cfg
        enabled_any $dep_any || disable $cfg

        if enabled $cfg; then
            eval dep_extralibs="\$${cfg}_extralibs"
            test -n "$dep_extralibs" && add_extralibs $dep_extralibs
        fi

        disable ${cfg}_checking
    done
}

print_config(){
    pfx=$1
    header=$2
    makefile=$3
    shift 3
    for cfg; do
        ucname="`toupper $cfg`"
        if enabled $cfg; then
            echo "#define ${pfx}${ucname} 1" >> $header
            echo "#define ENABLE_${ucname} 1" >> $header
            echo "${pfx}${ucname}=yes" >> $makefile
        else
            echo "#define ENABLE_${ucname} 0" >> $header
        fi
    done
}

flags_saved(){
    (: ${SAVE_CFLAGS?}) 2>/dev/null
}

save_flags(){
    flags_saved && return
    SAVE_CFLAGS="$CFLAGS"
    SAVE_LDFLAGS="$LDFLAGS"
    SAVE_extralibs="$extralibs"
}

restore_flags(){
    flags_saved || return
    CFLAGS="$SAVE_CFLAGS"
    LDFLAGS="$SAVE_LDFLAGS"
    extralibs="$SAVE_extralibs"
    unset SAVE_CFLAGS
    unset SAVE_LDFLAGS
    unset SAVE_extralibs
}

temp_cflags(){
    save_flags
    CFLAGS="$CFLAGS $*"
}

temp_ldflags(){
    save_flags
    LDFLAGS="$LDFLAGS $*"
}

temp_extralibs(){
    save_flags
    extralibs="$extralibs $*"
}

append(){
    var=$1
    shift
    flags_saved && eval "SAVE_$var=\"\$SAVE_$var $*\""
    eval "$var=\"\$$var $*\""
}

add_cflags(){
    append CFLAGS "$@"
}

add_ldflags(){
    append LDFLAGS "$@"
}

add_extralibs(){
    append extralibs "$@"
}

check_cmd(){
    log "$@"
    "$@" >>$logfile 2>&1
}

check_cc(){
    log check_cc "$@"
    cat >$TMPC
    log_file $TMPC
    check_cmd $cc $CFLAGS "$@" -c -o $TMPO $TMPC
}

check_cpp(){
    log check_cpp "$@"
    cat >$TMPC
    log_file $TMPC
    check_cmd $cc $CFLAGS "$@" -E -o $TMPO $TMPC
}

check_asm(){
    log check_asm "$@"
    name="$1"
    asm="$2"
    shift 2
    check_cc "$@" <<EOF && enable $name || disable $name
int foo(void){
    asm volatile($asm);
}
EOF
}

check_ld(){
    log check_ld "$@"
    check_cc || return
    flags=''
    libs=''
    for f; do
        test "${f}" = "${f#-l}" && flags="$flags $f" || libs="$libs $f"
    done
    check_cmd $cc $LDFLAGS $flags -o $TMPE $TMPO $extralibs $libs
}

check_cflags(){
    log check_cflags "$@"
    check_cc "$@" <<EOF && add_cflags "$@"
int x;
EOF
}

check_ldflags(){
    log check_ldflags "$@"
    check_ld "$@" <<EOF && add_ldflags "$@"
int main(){
    return 0;
}
EOF
}

check_header(){
    log check_header "$@"
    header=$1
    shift
    var=`echo $header | sed 's/[^A-Za-z0-9_]/_/g'`
    disable $var
    check_cpp "$@" <<EOF && enable $var
#include <$header>
int x;
EOF
}

check_func(){
    log check_func "$@"
    func=$1
    shift
    disable $func
    check_ld "$@" <<EOF && enable $func
extern int $func();
int main(){
    $func();
}
EOF
}

check_func2(){
    log check_func2 "$@"
    headers=$1
    func=$2
    shift 2
    disable $func
    incs=""
    for hdr in $headers; do
        incs="$incs
#include <$hdr>"
    done
    check_ld "$@" <<EOF && enable $func
$incs
int main(){
    (void) $func;
    return 0;
}
EOF
}

check_lib(){
    log check_lib "$@"
    header="$1"
    func="$2"
    shift 2
    temp_extralibs "$@"
    check_header $header && check_func $func && add_extralibs "$@"
    err=$?
    restore_flags
    return $err
}

check_lib2(){
    log check_lib2 "$@"
    headers="$1"
    func="$2"
    shift 2
    temp_extralibs "$@"
    check_func2 "$headers" $func && add_extralibs "$@"
    err=$?
    restore_flags
    return $err
}

check_exec(){
    check_ld "$@" && { enabled cross_compile || $TMPE >>$logfile 2>&1; }
}

check_exec_crash(){
    code=`cat`

    # exit() is not async signal safe.  _Exit (C99) and _exit (POSIX)
    # are safe but may not be available everywhere.  Thus we use
    # raise(SIGTERM) instead.  The check is run in a subshell so we
    # can redirect the "Terminated" message from the shell.  SIGBUS
    # is not defined by standard C so it is used conditionally.

    (check_exec "$@") >>$logfile 2>&1 <<EOF
#include <signal.h>
static void sighandler(int sig){
    raise(SIGTERM);
}
int main(){
    signal(SIGILL, sighandler);
    signal(SIGFPE, sighandler);
    signal(SIGSEGV, sighandler);
#ifdef SIGBUS
    signal(SIGBUS, sighandler);
#endif
    { $code }
}
EOF
}

require(){
    name="$1"
    header="$2"
    func="$3"
    shift 3
    check_lib $header $func "$@" || die "ERROR: $name not found"
}

require2(){
    name="$1"
    headers="$2"
    func="$3"
    shift 3
    check_lib2 "$headers" $func "$@" || die "ERROR: $name not found"
}

check_foo_config(){
    cfg=$1
    pkg=$2
    header=$3
    func=$4
    shift 4
    disable $cfg
    check_cmd ${pkg}-config --version
    err=$?
    if test "$err" = 0; then
        temp_cflags `${pkg}-config --cflags`
        temp_extralibs `${pkg}-config --libs`
        check_lib "$@" $header $func && enable $cfg
    fi
    return $err
}

apply(){
    file=$1
    shift
    "$@" < "$file" > "$file.tmp" && mv "$file.tmp" "$file" || rm "$file.tmp"
}

COMPONENT_LIST="
    bsfs
    decoders
    demuxers
    encoders
    muxers
    parsers
    protocols
"

CONFIG_LIST="
    $COMPONENT_LIST
    avisynth
    beos_netserver
    ffmpeg
    ffplay
    ffserver
    gpl
    gprof
    gray
    ipv6
    liba52
    liba52bin
    libamr
    libamr_nb
    libamr_wb
    libdc1394
    libfaac
    libfaad
    libfaadbin
    libgsm
    libmp3lame
    libnut
    libogg
    libtheora
    libvorbis
    libx264
    libxvid
    memalign_hack
    mpegaudio_hp
    network
    powerpc_perf
    pp
    small
    swscaler
    vhook
    x11grab
    zlib
"

THREADS_LIST='
    beosthreads
    pthreads
    w32threads
'

ARCH_LIST='
    alpha
    armv4l
    bfin
    ia64
    m68k
    mips
    parisc
    powerpc
    s390
    sh4
    sparc
    sparc64
    x86
    x86_32
    x86_64
'

ARCH_EXT_LIST='
    altivec
    armv5te
    armv6
    iwmmxt
    mmi
    mmx
    ssse3
    vis
'

HAVE_LIST="
    $ARCH_EXT_LIST
    $THREADS_LIST
    altivec_h
    arpa_inet_h
    byteswap_h
    closesocket
    cmov
    conio_h
    dcbzl
    dev_bktr_ioctl_bt848_h
    dev_bktr_ioctl_meteor_h
    dev_ic_bt8xx_h
    dev_video_meteor_ioctl_meteor_h
    dev_video_bktr_ioctl_bt848_h
    dlfcn_h
    dlopen
    ebp_available
    ebx_available
    fast_64bit
    fast_cmov
    fast_unaligned
    fork
    freetype2
    gethrtime
    GetProcessTimes
    getrusage
    imlib2
    inet_aton
    lrintf
    machine_ioctl_bt848_h
    machine_ioctl_meteor_h
    malloc_h
    memalign
    mkstemp
    mlib
    ppc64
    sdl
    sdl_video_size
    soundcard_h
    sys_poll_h
    sys_soundcard_h
    termios_h
    threads
    winsock2_h
"

CMDLINE_SELECT="
    $ARCH_EXT_LIST
    $CONFIG_LIST
    $THREADS_LIST
    debug
    extra_warnings
    shared
    static
"

# code dependency declarations

# architecture extensions
altivec_deps="powerpc"
armv5te_deps="armv4l"
armv6_deps="armv4l"
iwmmxt_deps="armv4l"
mmi_deps="mips"
mmx_deps="x86"
ssse3_deps="x86"
vis_deps="sparc"

# decoders / encoders
ac3_decoder_deps="gpl"
dxa_decoder_deps="zlib"
flashsv_decoder_deps="zlib"
flashsv_encoder_deps="zlib"
flv_decoder_deps="h263_decoder"
h263_decoder_deps="h263_parser mpeg4video_parser"
h263i_decoder_deps="h263_decoder"
h264_decoder_deps="h264_parser"
mpeg_xvmc_decoder_deps="xvmc"
mpeg4_decoder_deps="h263_decoder"
msmpeg4v1_decoder_deps="h263_decoder"
msmpeg4v2_decoder_deps="h263_decoder"
msmpeg4v3_decoder_deps="h263_decoder"
png_decoder_deps="zlib"
png_encoder_deps="zlib"
svq3_decoder_deps="h264_parser"
vc1_decoder_deps="h263_decoder"
wmv1_decoder_deps="h263_decoder"
wmv2_decoder_deps="h263_decoder"
wmv3_decoder_deps="h263_decoder"
zmbv_decoder_deps="zlib"
zmbv_encoder_deps="zlib"

# external libraries
liba52_decoder_deps="liba52"
liba52bin_decoder_extralibs='$ldl'
libamr_nb_decoder_deps="libamr_nb"
libamr_nb_encoder_deps="libamr_nb"
libamr_wb_decoder_deps="libamr_wb"
libamr_wb_encoder_deps="libamr_wb"
libfaac_encoder_deps="libfaac"
libfaad_decoder_deps="libfaad"
libfaadbin_decoder_extralibs='$ldl'
libgsm_decoder_deps="libgsm"
libgsm_encoder_deps="libgsm"
libgsm_ms_decoder_deps="libgsm"
libgsm_ms_encoder_deps="libgsm"
libmp3lame_encoder_deps="libmp3lame"
libtheora_encoder_deps="libtheora"
libvorbis_decoder_deps="libvorbis"
libvorbis_encoder_deps="libvorbis"
libx264_encoder_deps="libx264"
libxvid_encoder_deps="libxvid"
mpeg4aac_decoder_deps="libfaad"

# demuxers / muxers
ac3_demuxer_deps="ac3_parser"
audio_beos_demuxer_deps="audio_beos"
audio_beos_demuxer_extralibs="-lmedia -lbe"
audio_beos_muxer_deps="audio_beos"
audio_beos_muxer_extralibs="-lmedia -lbe"
avisynth_demuxer_deps="avisynth"
bktr_demuxer_deps_any="dev_bktr_ioctl_bt848_h machine_ioctl_bt848_h dev_video_bktr_ioctl_bt848_h dev_ic_bt8xx_h"
dv1394_demuxer_deps="dv1394"
libdc1394_demuxer_deps="libdc1394"
libnut_demuxer_deps="libnut"
libnut_muxer_deps="libnut"
mp3_demuxer_deps="mpegaudio_parser"
ogg_muxer_deps="libogg"
oss_demuxer_deps_any="soundcard_h sys_soundcard_h"
oss_muxer_deps_any="soundcard_h sys_soundcard_h"
redir_demuxer_deps="network"
rtp_muxer_deps="network mpegts_demuxer"
rtsp_demuxer_deps="rtp_protocol rtp_muxer"
sdp_demuxer_deps="rtsp_demuxer"
v4l2_demuxer_deps="linux_videodev2_h"
v4l_demuxer_deps="linux_videodev_h"
x11_grab_device_demuxer_deps="x11grab XShmCreateImage"
x11_grab_device_demuxer_extralibs="-lX11 -lXext"

# protocols
http_protocol_deps="network"
rtp_protocol_deps="udp_protocol"
tcp_protocol_deps="network"
udp_protocol_deps="network"

# programs
ffplay_deps="sdl"
ffserver_deps="muxers rtp_protocol"
ffserver_extralibs='$ldl'
vhook_extralibs='$ldl'


# set temporary file name
if test ! -z "$TMPDIR" ; then
    TMPDIR1="${TMPDIR}"
elif test ! -z "$TEMPDIR" ; then
    TMPDIR1="${TEMPDIR}"
else
    TMPDIR1="/tmp"
fi

TMPC="${TMPDIR1}/ffmpeg-conf-${RANDOM}-$$-${RANDOM}.c"
TMPO="${TMPDIR1}/ffmpeg-conf-${RANDOM}-$$-${RANDOM}.o"
TMPE="${TMPDIR1}/ffmpeg-conf-${RANDOM}-$$-${RANDOM}"
TMPS="${TMPDIR1}/ffmpeg-conf-${RANDOM}-$$-${RANDOM}.S"
TMPH="${TMPDIR1}/ffmpeg-conf-${RANDOM}-$$-${RANDOM}.h"

# default parameters

enable logging
logfile="config.err"

# installation paths
PREFIX="/usr/local"
libdir='$(PREFIX)/lib'
shlibdir="$libdir"
incdir='$(PREFIX)/include/ffmpeg'
mandir='$(PREFIX)/share/man'
bindir='$(PREFIX)/bin'

# toolchain
cc="gcc"
ar="ar"
ranlib="ranlib"
make="make"
strip="strip"
asmalign_pot="unknown"
ln_s="ln -sf"

# machine
arch=`uname -m`
cpu="generic"

# OS
targetos=$(tolower $(uname -s))

# libraries
enable zlib

# configurable options
enable debug
enable dostrip
enable ffmpeg
enable ffplay
enable ffserver
enable ipv6
enable static
enable mpegaudio_hp
enable network
enable optimize
enable protocols
vhook="default"

# build settings
SHFLAGS='-shared -Wl,-soname,$@'
VHOOKSHFLAGS='$(SHFLAGS)'
LDLATEFLAGS='-Wl,-rpath-link,\$(BUILD_ROOT)/libavcodec -Wl,-rpath-link,\$(BUILD_ROOT)/libavformat -Wl,-rpath-link,\$(BUILD_ROOT)/libavutil'
FFSERVERLDFLAGS=-Wl,-E
LDCONFIG="ldconfig"
LIBPREF="lib"
LIBSUF=".a"
LIB='$(LIBPREF)$(NAME)$(LIBSUF)'
SLIBPREF="lib"
SLIBSUF=".so"
SLIBNAME='$(SLIBPREF)$(NAME)$(SLIBSUF)'
SLIBNAME_WITH_VERSION='$(SLIBNAME).$(LIBVERSION)'
SLIBNAME_WITH_MAJOR='$(SLIBNAME).$(LIBMAJOR)'
LIB_INSTALL_EXTRA_CMD='$(RANLIB) "$(LIBDIR)/$(LIB)"'

# find source path
source_path="`dirname \"$0\"`"
enable source_path_used
if test -z "$source_path" -o "$source_path" = "." ; then
    source_path="`pwd`"
    disable source_path_used
else
    source_path="`cd \"$source_path\"; pwd`"
    echo "$source_path" | grep -q '[[:blank:]]' &&
      die "Out of tree builds are impossible with whitespace in source path."
fi

FFMPEG_CONFIGURATION="$@"

ENCODER_LIST=`sed -n 's/^[^#]*ENC.*(.*, *\(.*\)).*/\1_encoder/p' "$source_path/libavcodec/allcodecs.c"`
DECODER_LIST=`sed -n 's/^[^#]*DEC.*(.*, *\(.*\)).*/\1_decoder/p' "$source_path/libavcodec/allcodecs.c"`
PARSER_LIST=`sed -n 's/^[^#]*PARSER.*(.*, *\(.*\)).*/\1_parser/p' "$source_path/libavcodec/allcodecs.c"`
BSF_LIST=`sed -n 's/^[^#]*BSF.*(.*, *\(.*\)).*/\1_bsf/p' "$source_path/libavcodec/allcodecs.c"`
MUXER_LIST=`sed -n 's/^[^#]*_MUX.*(.*, *\(.*\)).*/\1_muxer/p' "$source_path/libavformat/allformats.c"`
DEMUXER_LIST=`sed -n 's/^[^#]*DEMUX.*(.*, *\(.*\)).*/\1_demuxer/p' "$source_path/libavformat/allformats.c"`
PROTOCOL_LIST=`sed -n 's/^[^#]*PROTOCOL.*(.*, *\(.*\)).*/\1_protocol/p' "$source_path/libavformat/allformats.c"`

enable $ENCODER_LIST $DECODER_LIST $PARSER_LIST $MUXER_LIST $DEMUXER_LIST $PROTOCOL_LIST $BSF_LIST
enable $ARCH_EXT_LIST

die_unknown(){
    echo "Unknown option \"$1\"."
    echo "See $0 --help for available options."
    exit 1
}

show_list() {
    for part in $*; do
        echo $part | sed 's/_[^_]*$//'
    done | sort
    exit 0
}

for opt do
  optval="${opt#*=}"
  case "$opt" in
  --log)
  ;;
  --log=*) logging="$optval"
  ;;
  --prefix=*) PREFIX="$optval"
  ;;
  --libdir=*) libdir="$optval"
  ;;
  --shlibdir=*) shlibdir="$optval"
  ;;
  --incdir=*) incdir="$optval"
  ;;
  --mandir=*) mandir="$optval"
  ;;
  --source-path=*) source_path="$optval"
  ;;
  --cross-prefix=*) cross_prefix="$optval"
  ;;
  --cross-compile) enable cross_compile
  ;;
  --target-os=*) targetos="$optval"
  ;;
  --cc=*) cc="$optval"
  ;;
  --make=*) make="$optval"
  ;;
  --extra-cflags=*) add_cflags "$optval"
  ;;
  --extra-ldflags=*) add_ldflags "$optval"
  ;;
  --extra-libs=*) add_extralibs "$optval"
  ;;
  --build-suffix=*) BUILDSUF="$optval"
  ;;
  --arch=*) arch="$optval"
  ;;
  --cpu=*) cpu="$optval"
  ;;
  --disable-opts) disable optimize
  ;;
  --enable-sunmlib) enable mlib
  ;;
  --disable-strip) disable dostrip
  ;;
  --disable-encoders) disable $ENCODER_LIST
  ;;
  --disable-decoders) disable $DECODER_LIST
  ;;
  --disable-muxers) disable $MUXER_LIST
  ;;
  --disable-demuxers) disable $DEMUXER_LIST
  ;;
  --disable-parsers) disable $PARSER_LIST
  ;;
  --disable-bsfs) disable $BSF_LIST
  ;;
  --disable-protocols) disable $PROTOCOL_LIST
  ;;
  --enable-*=*|--disable-*=*)
  eval `echo "$opt" | sed 's/=/-/;s/--/action=/;s/-/ thing=/;s/-/ name=/'`
  case "$thing" in
      encoder|decoder|muxer|demuxer|parser|bsf|protocol) $action ${optval}_${thing} ;;
      *) die_unknown "$opt" ;;
  esac
  ;;
  --enable-?*|--disable-?*)
  eval `echo "$opt" | sed 's/--/action=/;s/-/ option=/;s/-/_/g'`
  echo "$CMDLINE_SELECT" | grep -q "^ *$option\$" || die_unknown $opt
  $action $option
  ;;
  --list-*)
    NAME="${opt#--list-}"
    is_in $NAME $COMPONENT_LIST || die_unknown $opt
    NAME=$(toupper ${NAME%s})
    eval show_list \$${NAME}_LIST
  ;;
  --help|-h) show_help
  ;;
  *)
  die_unknown $opt
  ;;
  esac
done

case "$arch" in
  i386|i486|i586|i686|i86pc|BePC)
    arch="x86_32"
    enable fast_unaligned
  ;;
  x86_64|amd64)
    arch="x86_32"
    enable fast_unaligned
    canon_arch="`$cc -dumpmachine | sed -e 's,\([^-]*\)-.*,\1,'`"
    if [ x"$canon_arch" = x"x86_64" -o x"$canon_arch" = x"amd64" ]; then
      if [ -z "`echo $CFLAGS | grep -- -m32`"  ]; then
        arch="x86_64"
        enable fast_64bit
      fi
    fi
  ;;
  # armv4l is a subset of armv[567]*l
  arm|armv[4567]*l)
    arch="armv4l"
  ;;
  alpha)
    arch="alpha"
    enable fast_64bit
  ;;
  "Power Macintosh"|ppc|powerpc)
    arch="powerpc"
  ;;
  ppc64)
    arch="powerpc"
    enable fast_64bit
  ;;
  mips|mipsel|IP*)
    arch="mips"
  ;;
  sun4u|sparc64)
    arch="sparc64"
    enable fast_64bit
  ;;
  sparc)
    arch="sparc"
  ;;
  sh4)
    arch="sh4"
  ;;
  parisc)
    arch="parisc"
  ;;
  parisc64)
    arch="parisc"
    enable fast_64bit
  ;;
  s390|s390x)
    arch="s390"
  ;;
  m68k)
    arch="m68k"
  ;;
  ia64)
    arch="ia64"
    enable fast_64bit
  ;;
  bfin)
    arch="bfin"
  ;;
  *)
    arch="unknown"
  ;;
esac

enable $arch
enabled_any x86_32 x86_64 && enable x86
enabled     sparc64       && enable sparc

# OS specific
case $targetos in
  beos|haiku|zeta)
    PREFIX="$HOME/config"
    # helps building libavcodec
    add_cflags "-DPIC -fomit-frame-pointer"
    # 3 gcc releases known for BeOS, each with ugly bugs
    gcc_version="`$cc -v 2>&1 | grep version | cut -d ' ' -f3-`"
    case "$gcc_version" in
      2.9-beos-991026*|2.9-beos-000224*) echo "R5/GG gcc"
        disable mmx
        ;;
      *20010315*) echo "BeBits gcc"
        add_cflags "-fno-expensive-optimizations"
        ;;
    esac
    LDCONFIG="echo ignoring ldconfig"
    SHFLAGS=-nostart
    # enable BeOS things
    enable audio_beos
    # no need for libm, but the inet stuff
    # Check for BONE
    # XXX: actually should check for NOT net_server
    if (echo $BEINCLUDES|grep 'headers/be/bone' >/dev/null); then
        network_extralibs="-lbind -lsocket"
    else
        enable beos_netserver
        network_extralibs="-lnet"
    fi ;;
  sunos)
    FFSERVERLDFLAGS=""
    SHFLAGS="-shared -Wl,-h,\$@"
    network_extralibs="-lsocket -lnsl"
    ;;
  netbsd)
    oss_demuxer_extralibs="-lossaudio"
    oss_muxer_extralibs="-lossaudio"
    ;;
  openbsd)
    disable need_memalign
    LIBOBJFLAGS="\$(PIC)"
    LDCONFIG="ldconfig -m \$(SHLIBDIR)"
    SHFLAGS='-shared'
    SLIBNAME='$(SLIBPREF)$(NAME)$(SLIBSUF).$(LIBVERSION)'
    SLIBNAME_WITH_VERSION='$(SLIBNAME)'
    SLIBNAME_WITH_MAJOR='$(SLIBNAME)'
    oss_demuxer_extralibs="-lossaudio"
    oss_muxer_extralibs="-lossaudio"
    ;;
  freebsd)
    disable need_memalign
    ;;
  bsd/os)
    osextralibs="-lpoll -lgnugetopt"
    strip="strip -d"
    ;;
  darwin)
    disable need_memalign
    SHFLAGS="-dynamiclib -Wl,-single_module -Wl,-install_name,\$(SHLIBDIR)/\$(SLIBNAME),-current_version,\$(SPPVERSION),-compatibility_version,\$(SPPVERSION) -Wl,-read_only_relocs,suppress"
    VHOOKSHFLAGS='-dynamiclib -Wl,-single_module -flat_namespace -undefined suppress -Wl,-install_name,$(SHLIBDIR)/vhook/$@'
    strip="strip -x"
    FFLDFLAGS="-Wl,-dynamic,-search_paths_first"
    SLIBSUF=".dylib"
    SLIBNAME_WITH_VERSION='$(SLIBPREF)$(NAME).$(LIBVERSION)$(SLIBSUF)'
    SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(NAME).$(LIBMAJOR)$(SLIBSUF)'
    FFSERVERLDFLAGS=-Wl,-bind_at_load
    ;;
  mingw32*)
    targetos=mingw32
    shlibdir="$bindir"
    VHOOKSHFLAGS='-shared -L$(BUILD_ROOT)/libavformat -L$(BUILD_ROOT)/libavcodec -L$(BUILD_ROOT)/libavutil'
    VHOOKLIBS='-lavformat$(BUILDSUF) -lavcodec$(BUILDSUF) -lavutil$(BUILDSUF) $(EXTRALIBS)'
    if enabled swscaler; then
        VHOOKSHFLAGS="$VHOOKSHFLAGS -L\$(BUILD_ROOT)/libswscale"
        VHOOKLIBS="$VHOOKLIBS -lswscale\$(BUILDSUF)"
    fi
    disable ffserver
    SLIBPREF=""
    SLIBSUF=".dll"
    EXESUF=".exe"
    SLIBNAME_WITH_VERSION='$(SLIBPREF)$(NAME)-$(LIBVERSION)$(SLIBSUF)'
    SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(NAME)-$(LIBMAJOR)$(SLIBSUF)'
    SLIB_EXTRA_CMD="-lib /machine:i386 /def:\$(@:${SLIBSUF}=.def)"
    SLIB_INSTALL_EXTRA_CMD="-install -m 644 \$(SLIBNAME_WITH_MAJOR:\$(SLIBSUF)=.lib) \"\$(SHLIBDIR)/\$(SLIBNAME_WITH_MAJOR:\$(SLIBSUF)=.lib)\""
    SHFLAGS="-shared -Wl,--output-def,\$(@:${SLIBSUF}=.def),--out-implib,lib\$(SLIBNAME:\$(SLIBSUF)=.dll.a) -Wl,--enable-runtime-pseudo-reloc -Wl,--enable-auto-image-base"
    ;;
  cygwin*)
    targetos=cygwin
    shlibdir="$bindir"
    VHOOKSHFLAGS='-shared -L$(BUILD_ROOT)/libavformat -L$(BUILD_ROOT)/libavcodec -L$(BUILD_ROOT)/libavutil'
    VHOOKLIBS='-lavformat$(BUILDSUF) -lavcodec$(BUILDSUF) -lavutil$(BUILDSUF) $(EXTRALIBS)'
    if enabled swscaler; then
        VHOOKSHFLAGS="$VHOOKSHFLAGS -L\$(BUILD_ROOT)/libswscale"
        VHOOKLIBS="$VHOOKLIBS -lswscale\$(BUILDSUF)"
    fi
    EXESUF=".exe"
    SLIBPREF="cyg"
    SLIBSUF=".dll"
    SLIBNAME_WITH_VERSION='$(SLIBPREF)$(NAME)-$(LIBVERSION)$(SLIBSUF)'
    SLIBNAME_WITH_MAJOR='$(SLIBPREF)$(NAME)-$(LIBMAJOR)$(SLIBSUF)'
    SHFLAGS='-shared -Wl,--out-implib=lib$(NAME).dll.a -Wl,--enable-auto-image-base'
    ;;
  linux)
    LDLATEFLAGS="-Wl,--as-needed $LDLATEFLAGS"
    enable dv1394
    ;;
  irix*)
    targetos=irix
    ranlib="echo ignoring ranlib"
    ;;
  *)
    targetos="${targetos}-UNKNOWN"
    ;;
esac

add_extralibs $osextralibs

if ! disabled logging ; then
    enabled logging || logfile="$logging"
    echo "# $0 $@" >$logfile
    set >>$logfile
else
    logfile=/dev/null
fi

# Combine FFLDFLAGS and the LDFLAGS environment variable.
LDFLAGS="$FFLDFLAGS $LDFLAGS"

test -n "$cross_prefix" && enable cross_compile
cc="${cross_prefix}${cc}"
ar="${cross_prefix}${ar}"
ranlib="${cross_prefix}${ranlib}"
strip="${cross_prefix}${strip}"

# we need to build at least one lib type
if ! enabled_any static shared; then
    cat <<EOF
At least one library type must be built.
Specify --enable-static to build the static libraries or --enable-shared to
build the shared libraries as well. To only build the shared libraries specify
--disable-static in addition to --enable-shared.
EOF
    exit 1;
fi

if disabled static; then
    LIB=""
fi

if ! enabled libogg; then
    enabled libtheora && die "libogg must be enabled to enable libtheora."
    enabled libvorbis && die "libogg must be enabled to enable libvorbis."
fi

if enabled_any libfaad libfaadbin ; then
    if check_header faad.h; then
        check_cc << EOF
#include <faad.h>
#ifndef FAAD2_VERSION
ok faad1
#endif
int main( void ) { return 0; }
EOF
        test $? = 0 && enable libfaad2
    else
        die "FAAD test failed."
    fi
fi


if ! enabled gpl; then
    die_gpl_disabled(){
        name=$1
        shift
        enabled_any $@ && die "$name is under GPL and --enable-gpl is not specified."
    }
    die_gpl_disabled "The Postprocessing code" pp
    die_gpl_disabled "liba52"                  liba52
    die_gpl_disabled "libx264"                 libx264
    die_gpl_disabled "libxvidcore"             libxvid
    die_gpl_disabled "FAAD2"                   libfaad2
    die_gpl_disabled "The X11 grabber"         x11grab
    die_gpl_disabled "The software scaler"     swscaler
fi

check_deps $ARCH_EXT_LIST

test -z "$need_memalign" && need_memalign="$mmx"

#Darwin CC versions
if test $targetos = darwin; then
    if test -n "`$cc -v 2>&1 | grep xlc`"; then
        add_cflags "-qpdf2 -qlanglvl=extc99 -qmaxmem=-1 -qarch=auto -qtune=auto"
    else
        add_cflags "-no-cpp-precomp -pipe"
        check_cflags "-force_cpusubtype_ALL"
        check_cflags "-Wno-sign-compare"
        disabled shared && add_cflags -mdynamic-no-pic
    fi
fi

disabled optimize || add_cflags -fomit-frame-pointer

# Add processor-specific flags
if test $cpu != "generic"; then
    warn_altivec(){
        $1 altivec && echo "WARNING: Tuning for $2 but AltiVec $1.";
    }
    case $cpu in
        601|ppc601|PowerPC601)
            add_cflags "-mcpu=601"
            warn_altivec enabled PPC601
        ;;
        603*|ppc603*|PowerPC603*)
            add_cflags "-mcpu=603"
            warn_altivec enabled PPC603
        ;;
        604*|ppc604*|PowerPC604*)
            add_cflags "-mcpu=604"
            warn_altivec enabled PPC604
        ;;
        G3|g3|75*|ppc75*|PowerPC75*)
            add_cflags "-mcpu=750 -mpowerpc-gfxopt"
            warn_altivec enabled PPC75x
        ;;
        G4|g4|745*|ppc745*|PowerPC745*)
            add_cflags "-mcpu=7450 -mpowerpc-gfxopt"
            warn_altivec disabled PPC745x
        ;;
        74*|ppc74*|PowerPC74*)
            add_cflags "-mcpu=7400 -mpowerpc-gfxopt"
            warn_altivec disabled PPC74xx
        ;;
        G5|g5|970|ppc970|PowerPC970|power4*|Power4*)
            add_cflags "-mcpu=970 -mpowerpc-gfxopt -mpowerpc64"
            warn_altivec disabled PPC970
            enable ppc64
        ;;
        Cell|CELL|cell)
            add_cflags "-mcpu=cell"
            warn_altivec disabled Cell
            enable ppc64
        ;;
        # targets that do NOT support conditional mov (cmov)
        i[345]86|pentium|pentium-mmx|k6|k6-[23]|winchip-c6|winchip2|c3)
            add_cflags "-march=$cpu"
            disable cmov
        ;;
        # targets that do support conditional mov (cmov)
        i686|pentiumpro|pentium[23]|pentium-m|athlon|athlon-tbird|athlon-4|athlon-[mx]p|athlon64|k8|opteron|athlon-fx|core2)
            add_cflags "-march=$cpu"
            enable cmov
            enable fast_cmov
        ;;
        # targets that do support conditional mov but on which it's slow
        pentium4|prescott|nocona)
            add_cflags "-march=$cpu"
            enable cmov
            disable fast_cmov
        ;;
        sparc64)
            add_cflags "-mcpu=v9"
        ;;
        bf*) #bf531 bf532 bf533 bf561 bf5xx all get this config
            add_cflags "-mfdpic"
            add_ldflags "-mfdpic"
        ;;
        arm*)
            add_cflags "-mcpu=$cpu"
        ;;
        *)
        echo "WARNING: Unknown CPU \"$cpu\", ignored."
        ;;
    esac
fi

gnu_make(){
    $1 --version 2>&1 | grep -q GNU
}

if ! gnu_make $make; then
    gnu_make gmake && make=gmake || die "GNU make not found."
fi

# make sure we can execute files in $TMPDIR
cat >$TMPE 2>>$logfile <<EOF
#! /bin/sh
EOF
chmod +x $TMPE >>$logfile 2>&1
if ! $TMPE >>$logfile 2>&1; then
    cat <<EOF
Unable to create and execute files in $TMPDIR1.  Set the TMPDIR environment
variable to another directory and make sure that $TMPDIR1 is not mounted
noexec.
EOF
    die "Sanity test failed."
fi
rm $TMPE

# compiler sanity check
check_exec <<EOF
int main(){
    return 0;
}
EOF
if test "$?" != 0; then
    echo "$cc is unable to create an executable file."
    if test -z "$cross_prefix" && ! enabled cross_compile ; then
        echo "If $cc is a cross-compiler, use the --cross-compile option."
        echo "Only do this if you know what cross compiling means."
    fi
    die "C compiler test failed."
fi

if enabled x86; then
    # check whether EBP is available on x86
    # As 'i' is stored on the stack, this program will crash
    # if the base pointer is used to access it because the
    # base pointer is cleared in the inline assembly code.
    check_exec_crash <<EOF && enable ebp_available
    volatile int i=0;
    asm volatile (
        "xorl %%ebp, %%ebp"
    ::: "%ebp");
    return i;
EOF

    # check wether EBX is available on x86
    check_asm ebx_available '"":::"%ebx"'

    # check whether binutils is new enough to compile SSSE3
    enabled ssse3 && check_asm ssse3 '"pabsw %xmm0, %xmm0"'
fi

# check for assembler specific support

if test $arch = "powerpc"; then
check_cc <<EOF && enable dcbzl
int main(void) {
    register long zero = 0;
    char data[1024];
    asm volatile("dcbzl %0, %1" : : "b" (data), "r" (zero));
return 0;
}
EOF
fi

# check for SIMD availability

# AltiVec flags: The FSF version of GCC differs from the Apple version
if enabled altivec; then
    test -n "`$cc -v 2>&1 | grep version | grep Apple`" &&
        add_cflags "-faltivec" ||
        add_cflags "-maltivec -mabi=altivec"

    check_header altivec.h

    # check if our compiler supports Motorola AltiVec C API
    enabled altivec_h &&
        inc_altivec_h="#include <altivec.h>" ||
        inc_altivec_h=
    check_cc <<EOF || disable altivec
$inc_altivec_h
int main(void) {
    vector signed int v1, v2, v3;
    v1 = vec_add(v2,v3);
    return 0;
}
EOF
fi

enabled armv5te && check_asm armv5te '"qadd r0, r0, r0"'
enabled armv6   && check_asm armv6   '"sadd16 r0, r0, r0"'
enabled iwmmxt  && check_asm iwmmxt  '"wunpckelub wr6, wr4"'
enabled mmi     && check_asm mmi     '"lq $2, 0($2)"'
enabled vis     && check_asm vis     '"pdist %f0, %f0, %f0"' -mcpu=ultrasparc

enabled vis && add_cflags "-mcpu=ultrasparc -mtune=ultrasparc"

# ---
# big/little-endian test
check_cc <<EOF || die "endian test failed"
unsigned int endian = 'B' << 24 | 'I' << 16 | 'G' << 8 | 'E';
EOF
grep -q BIGE $TMPO && enable bigendian

# ---
# check availability of some header files

if check_func dlopen; then
    ldl=
elif check_func dlopen -ldl; then
    ldl=-ldl
fi

check_func fork
check_func gethrtime
check_func getrusage
check_func inet_aton
check_func memalign
check_func mkstemp
check_func2 windows.h GetProcessTimes

check_header byteswap.h
check_header conio.h
check_header dlfcn.h
check_header malloc.h
check_header termios.h

if ! enabled_any memalign memalign_hack && enabled need_memalign ; then
    die "Error, no memalign() but SSE enabled, disable it or use --enable-memalign-hack."
fi

enabled zlib && check_lib zlib.h zlibVersion -lz || disable zlib

# ffserver uses poll(),
# if it's not found we can emulate it using select().
if enabled ffserver; then
    check_header sys/poll.h
fi

# check for some common methods of building with pthread support
# do this before the optional library checks as some of them require pthreads
if enabled pthreads; then
    if check_func pthread_create; then
        :
    elif check_func pthread_create -pthread; then
        add_cflags -pthread
        add_ldflags -pthread
    elif check_func pthread_create -pthreads; then
        add_cflags -pthreads
        add_ldflags -pthreads
    elif ! check_lib pthread.h pthread_create -lpthread; then
        die "ERROR: can't find pthreads library"
    fi
fi

for thread in $THREADS_LIST; do
    if enabled $thread; then
        test -n "$thread_type" &&
            die "ERROR: Only one thread type must be selected." ||
            thread_type="$thread"
    fi
done

check_lib math.h sin -lm

# test for lrintf in math.h
check_exec <<EOF && enable lrintf || disable lrintf
#define _ISOC9X_SOURCE  1
#include <math.h>
int main( void ) { return (lrintf(3.999f) > 0)?0:1; }
EOF

enabled_any libamr_nb libamr_wb && enable libamr

# these are off by default, so fail if requested and not available
enabled avisynth   && require2 vfw32 "windows.h vfw.h" AVIFileInit -lvfw32
enabled liba52     && require liba52 a52dec/a52.h a52_init -la52
enabled libamr_nb  && require libamrnb amrnb/interf_dec.h Speech_Decode_Frame_init -lamrnb -lm
enabled libamr_wb  && require libamrwb amrwb/dec_if.h D_IF_init -lamrwb -lm
enabled libdc1394  && require libdc1394 libdc1394/dc1394_control.h dc1394_create_handle -ldc1394_control -lraw1394
enabled libfaac    && require2 libfaac "stdint.h faac.h" faacEncGetVersion -lfaac
enabled libfaad    && require2 libfaad faad.h faacDecOpen -lfaad
enabled libgsm     && require libgsm gsm.h gsm_create -lgsm
enabled libmp3lame && require LAME lame/lame.h lame_init -lmp3lame -lm
enabled libnut     && require libnut libnut.h nut_demuxer_init -lnut
enabled libogg     && require libogg ogg/ogg.h ogg_sync_init -logg
enabled libtheora  && require libtheora theora/theora.h theora_info_init -ltheora -logg
enabled libvorbis  && require libvorbis vorbis/vorbisenc.h vorbis_info_init -lvorbis -lvorbisenc -logg
enabled libx264    && require x264 x264.h x264_encoder_open -lx264
enabled libxvid    && require Xvid xvid.h xvid_global -lxvidcore
enabled mlib       && require mediaLib mlib_types.h mlib_VectorSub_S16_U8_Mod -lmlib

# disable the native AC-3 decoder if liba52 is enabled
enabled liba52 && disable ac3_decoder

_restrict=
for restrict_keyword in restrict __restrict__ __restrict; do
    check_cc <<EOF && _restrict=$restrict_keyword && break
void foo(char * $restrict_keyword p);
EOF
done

test "$vhook" = "default" && vhook="$dlopen"

if test "$targetos" = cygwin -o "$targetos" = mingw32 && enabled_all static vhook ; then
    disable vhook
    echo
    echo "At the moment vhooks don't work on Cygwin or MinGW static builds."
    echo "Patches welcome."
    echo
fi

if enabled vhook; then
    check_ldflags -rdynamic
    check_ldflags -export-dynamic
fi

check_foo_config imlib2 imlib2 Imlib2.h imlib_load_font
check_foo_config freetype2 freetype ft2build.h FT_Init_FreeType

##########################################
# SDL check

disable sdl_too_old
disable sdl
SDL_CONFIG="${cross_prefix}sdl-config"
if "${SDL_CONFIG}" --version >/dev/null 2>&1; then
    sdl_cflags=`"${SDL_CONFIG}" --cflags`
    temp_cflags $sdl_cflags
    temp_extralibs `"${SDL_CONFIG}" --libs`
    if check_lib SDL.h SDL_Init; then
        _sdlversion=`"${SDL_CONFIG}" --version | sed 's/[^0-9]//g'`
        if test "$_sdlversion" -lt 121 ; then
            enable sdl_too_old
        else
            enable sdl
            check_cc $sdl_cflags <<EOF && enable sdl_video_size
#include <SDL.h>
int main(void){
    const SDL_VideoInfo *vi = SDL_GetVideoInfo();
    int w = vi->current_w;
    return 0;
}
EOF
        fi
    fi
    restore_flags
fi

texi2html -version >/dev/null 2>&1 && enable texi2html || disable texi2html

##########################################
# Network check

if enabled network; then
    # Prefer arpa/inet.h over winsock2
    if check_header arpa/inet.h ; then
        check_func closesocket
    elif check_header winsock2.h ; then
        network_extralibs="-lws2_32"
        check_func2 winsock2.h closesocket
    fi
fi

##########################################
# IPv6 check

enabled network && enabled ipv6 && check_ld <<EOF && enable ipv6 || disable ipv6
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main( void ) {
  struct sockaddr_storage saddr;
  struct ipv6_mreq mreq6;
  getaddrinfo(0,0,0,0);
  getnameinfo(0,0,0,0,0,0,0);
  IN6_IS_ADDR_MULTICAST((const struct in6_addr *)0);
}
EOF

check_header linux/videodev.h
check_header linux/videodev2.h

# check for ioctl_meteor.h, ioctl_bt848.h and alternatives
{ check_header dev/bktr/ioctl_meteor.h &&
  check_header dev/bktr/ioctl_bt848.h; } ||
{ check_header machine/ioctl_meteor.h &&
  check_header machine/ioctl_bt848.h; } ||
{ check_header dev/video/meteor/ioctl_meteor.h &&
  check_header dev/video/bktr/ioctl_bt848.h; } ||
check_header dev/ic/bt8xx.h

check_header sys/soundcard.h
check_header soundcard.h

# Deal with the x11 frame grabber
enabled x11grab                         &&
check_header X11/Xlib.h                 &&
check_header X11/extensions/XShm.h      &&
check_func XOpenDisplay -lX11           &&
check_func XShmCreateImage -lX11 -lXext

enabled debug && add_cflags -g

# add some useful compiler flags if supported
check_cflags -Wdeclaration-after-statement
check_cflags -Wall
check_cflags -Wno-switch
check_cflags -Wdisabled-optimization
check_cflags -Wpointer-arith
check_cflags -Wredundant-decls
check_cflags -Wno-pointer-sign
enabled extra_warnings && check_cflags -Winline

# add some linker flags
check_ldflags -Wl,--warn-common
check_ldflags $LDLATEFLAGS

if enabled small; then
    check_cflags -Os            # not all compilers support -Os
    optimize="small"
elif enabled optimize; then
    if test -n "`$cc -v 2>&1 | grep xlc`"; then
        add_cflags  "-O5"
        add_ldflags "-O5"
    else
        add_cflags "-O3"
    fi
fi

# PIC flags for shared library objects where they are needed
if enabled shared; then
    # LIBOBJFLAGS may have already been set in the OS configuration
    if test -z "$LIBOBJFLAGS" ; then
        case "$arch" in
            x86_64|ia64|alpha|sparc*|power*) LIBOBJFLAGS="\$(PIC)" ;;
        esac
    fi
fi

if enabled gprof; then
    add_cflags  "-p"
    add_ldflags "-p"
fi

VHOOKCFLAGS="-fPIC"

# find if .align arg is power-of-two or not
if test $asmalign_pot = "unknown"; then
    disable asmalign_pot
    echo 'asm (".align 3");' | check_cc && enable asmalign_pot
fi

enabled_any $ENCODER_LIST  && enable encoders
enabled_any $DECODER_LIST  && enable decoders
enabled_any $MUXER_LIST    && enable muxers
enabled_any $DEMUXER_LIST  && enable demuxers
enabled_any $PROTOCOL_LIST && enable protocols
enabled_any $BSF_LIST      && enable bsfs

enabled_any $THREADS_LIST  && enable threads

check_deps $CONFIG_LIST $HAVE_LIST $DECODER_LIST $ENCODER_LIST $PARSER_LIST \
    $BSF_LIST $DEMUXER_LIST $MUXER_LIST $PROTOCOL_LIST

enabled libdc1394 && append pkg_requires "libraw1394"
enabled libogg    && append pkg_requires "ogg >= 1.1"
enabled libtheora && append pkg_requires "theora"
enabled libvorbis && append pkg_requires "vorbis vorbisenc"

echo "install prefix            $PREFIX"
echo "source path               $source_path"
echo "C compiler                $cc"
echo "make                      $make"
echo ".align is power-of-two    $asmalign_pot"
echo "ARCH                      $arch ($cpu)"
if test "$BUILDSUF" != ""; then
    echo "build suffix              $BUILDSUF"
fi
echo "big-endian                ${bigendian-no}"
if test $arch = "x86_32" -o $arch = "x86_64"; then
    echo "MMX enabled               ${mmx-no}"
    echo "CMOV enabled              ${cmov-no}"
    echo "CMOV is fast              ${fast_cmov-no}"
    echo "EBX available             ${ebx_available-no}"
    echo "EBP available             ${ebp_available-no}"
fi
if test $arch = "armv4l"; then
    echo "ARMv5TE enabled           ${armv5te-no}"
    echo "ARMv6 enabled             ${armv6-no}"
    echo "IWMMXT enabled            ${iwmmxt-no}"
fi
if test $arch = "mips"; then
    echo "MMI enabled               ${mmi-no}"
fi
if test $arch = "powerpc"; then
    echo "AltiVec enabled           ${altivec-no}"
    echo "dcbzl available           ${dcbzl-no}"
fi
echo "gprof enabled             ${gprof-no}"
echo "debug symbols             ${debug-no}"
echo "strip symbols             ${dostrip-no}"
echo "optimize                  ${optimize-no}"
echo "static                    ${static-no}"
echo "shared                    ${shared-no}"
echo "postprocessing support    ${pp-no}"
echo "software scaler enabled   ${swscaler-no}"
echo "video hooking             ${vhook-no}"
if enabled vhook; then
    echo "Imlib2 support            ${imlib2-no}"
    echo "FreeType support          ${freetype2-no}"
fi
echo "network support           ${network-no}"
if enabled network; then
    echo "IPv6 support              ${ipv6-no}"
fi
echo "threading support         ${thread_type-no}"
echo "SDL support               ${sdl-no}"
if enabled sdl_too_old; then
    echo "-> Your SDL version is too old - please upgrade to have FFplay/SDL support."
fi
echo "Sun medialib support      ${mlib-no}"
echo "AVISynth enabled          ${avisynth-no}"
echo "liba52 support            ${liba52-no}"
echo "liba52 dlopened           ${liba52bin-no}"
echo "libamr-nb support         ${libamr_nb-no}"
echo "libamr-wb support         ${libamr_wb-no}"
echo "libdc1394 support         ${libdc1394-no}"
echo "libfaac enabled           ${libfaac-no}"
echo "libfaad enabled           ${libfaad-no}"
echo "libfaad dlopened          ${libfaadbin-no}"
echo "libgsm enabled            ${libgsm-no}"
echo "libmp3lame enabled        ${libmp3lame-no}"
echo "libnut enabled            ${libnut-no}"
echo "libogg enabled            ${libogg-no}"
echo "libtheora enabled         ${libtheora-no}"
echo "libvorbis enabled         ${libvorbis-no}"
echo "x264 enabled              ${libx264-no}"
echo "XviD enabled              ${libxvid-no}"
echo "zlib enabled              ${zlib-no}"
enabled gpl &&
    echo "License: GPL" ||
    echo "License: LGPL"

echo "Creating config.mak and config.h..."

echo "# Automatically generated by configure - do not modify!" > config.mak
echo "/* Automatically generated by configure - do not modify! */" > $TMPH
echo "#define FFMPEG_CONFIGURATION \"$FFMPEG_CONFIGURATION\"" >> $TMPH

echo "PREFIX=$PREFIX" >> config.mak
echo "prefix=\$(DESTDIR)\$(PREFIX)" >> config.mak
echo "LIBDIR=\$(DESTDIR)$libdir" >> config.mak
echo "SHLIBDIR=\$(DESTDIR)$shlibdir" >> config.mak
echo "INCDIR=\$(DESTDIR)$incdir" >> config.mak
echo "BINDIR=\$(DESTDIR)$bindir" >> config.mak
echo "MANDIR=\$(DESTDIR)$mandir" >> config.mak
echo "MAKE=$make" >> config.mak
echo "CC=$cc" >> config.mak
echo "AR=$ar" >> config.mak
echo "RANLIB=$ranlib" >> config.mak
echo "LDCONFIG=$LDCONFIG" >> config.mak
echo "LN_S=$ln_s" >> config.mak
enabled dostrip &&
    echo "STRIP=$strip" >> config.mak ||
    echo "STRIP=echo ignoring strip" >> config.mak

echo "OPTFLAGS=$CFLAGS" >> config.mak
echo "VHOOKCFLAGS=$VHOOKCFLAGS">>config.mak
echo "LDFLAGS=$LDFLAGS" >> config.mak
echo "FFSERVERLDFLAGS=$FFSERVERLDFLAGS" >> config.mak
echo "SHFLAGS=$SHFLAGS" >> config.mak
echo "VHOOKSHFLAGS=$VHOOKSHFLAGS" >> config.mak
echo "VHOOKLIBS=$VHOOKLIBS" >> config.mak
echo "LIBOBJFLAGS=$LIBOBJFLAGS" >> config.mak
echo "BUILD_STATIC=$static" >> config.mak
echo "BUILDSUF=$BUILDSUF" >> config.mak
echo "LIBPREF=$LIBPREF" >> config.mak
echo "LIBSUF=\${BUILDSUF}$LIBSUF" >> config.mak
echo "LIB=$LIB" >> config.mak
echo "SLIBPREF=$SLIBPREF" >> config.mak
echo "SLIBSUF=\${BUILDSUF}$SLIBSUF" >> config.mak
echo "EXESUF=\${BUILDSUF}$EXESUF" >> config.mak

if enabled bigendian; then
  echo "WORDS_BIGENDIAN=yes" >> config.mak
  echo "#define WORDS_BIGENDIAN 1" >> $TMPH
fi
if enabled mmx; then
  echo "#define __CPU__ 586" >> $TMPH
fi

if enabled sdl; then
  echo "SDL_LIBS=`"${SDL_CONFIG}" --libs`" >> config.mak
  echo "SDL_CFLAGS=`"${SDL_CONFIG}" --cflags`" >> config.mak
fi
if enabled texi2html; then
  echo "BUILD_DOC=yes" >> config.mak
fi

sws_version=`grep '#define LIBSWSCALE_VERSION ' "$source_path/libswscale/swscale.h" | sed 's/[^0-9\.]//g'`
pp_version=`grep '#define LIBPOSTPROC_VERSION ' "$source_path/libpostproc/postprocess.h" | sed 's/[^0-9\.]//g'`
lavc_version=`grep '#define LIBAVCODEC_VERSION ' "$source_path/libavcodec/avcodec.h" | sed 's/[^0-9\.]//g'`
lavf_version=`grep '#define LIBAVFORMAT_VERSION ' "$source_path/libavformat/avformat.h" | sed 's/[^0-9\.]//g'`
lavu_version=`grep '#define LIBAVUTIL_VERSION ' "$source_path/libavutil/avutil.h" | sed 's/[^0-9\.]//g'`



if enabled shared; then
  echo "BUILD_SHARED=yes" >> config.mak
  echo "PIC=-fPIC -DPIC" >> config.mak
  echo "SPPMAJOR=${pp_version%%.*}" >> config.mak
  echo "SPPVERSION=$pp_version" >> config.mak
  echo "LAVCMAJOR=${lavc_version%%.*}" >> config.mak
  echo "LAVCVERSION=$lavc_version" >> config.mak
  echo "LAVFMAJOR=${lavf_version%%.*}" >> config.mak
  echo "LAVFVERSION=$lavf_version" >> config.mak
  echo "LAVUMAJOR=${lavu_version%%.*}" >> config.mak
  echo "LAVUVERSION=$lavu_version" >> config.mak
  echo "SWSMAJOR=${sws_version%%.*}" >> config.mak
  echo "SWSVERSION=$sws_version" >> config.mak
  echo "SLIBNAME=${SLIBNAME}" >> config.mak
  echo "SLIBNAME_WITH_VERSION=${SLIBNAME_WITH_VERSION}" >> config.mak
  echo "SLIBNAME_WITH_MAJOR=${SLIBNAME_WITH_MAJOR}" >> config.mak
  echo "SLIB_EXTRA_CMD=${SLIB_EXTRA_CMD}" >> config.mak
  echo "SLIB_INSTALL_EXTRA_CMD=${SLIB_INSTALL_EXTRA_CMD}" >> config.mak
fi
echo "LIB_INSTALL_EXTRA_CMD=${LIB_INSTALL_EXTRA_CMD}" >> config.mak
echo "EXTRALIBS=$extralibs" >> config.mak

print_config ARCH_   $TMPH config.mak $ARCH_LIST
print_config HAVE_   $TMPH config.mak $HAVE_LIST
print_config CONFIG_ $TMPH config.mak $CONFIG_LIST   \
                                      $DECODER_LIST  \
                                      $ENCODER_LIST  \
                                      $PARSER_LIST   \
                                      $BSF_LIST      \
                                      $DEMUXER_LIST  \
                                      $MUXER_LIST    \
                                      $PROTOCOL_LIST \

echo "#define restrict $_restrict" >> $TMPH

if enabled small; then
  echo "#define av_always_inline"  >> $TMPH
fi

echo "SRC_PATH=\"$source_path\"" >> config.mak
echo "SRC_PATH_BARE=$source_path" >> config.mak
echo "BUILD_ROOT=\"$PWD\"" >> config.mak

# Apparently it's not possible to portably echo a backslash.
enabled asmalign_pot &&
  printf '#define ASMALIGN(ZEROBITS) ".align " #ZEROBITS "\\n\\t"\n' >> $TMPH ||
  printf '#define ASMALIGN(ZEROBITS) ".align 1<<" #ZEROBITS "\\n\\t"\n' >> $TMPH


# Do not overwrite config.h if unchanged to avoid superfluous rebuilds.
cmp -s $TMPH config.h &&
    echo "config.h is unchanged" ||
    mv -f $TMPH config.h

rm -f $TMPO $TMPC $TMPE $TMPS $TMPH

# build tree in object directory if source path is different from current one
if enabled source_path_used; then
    DIRS="\
         doc \
         libavcodec \
         libavcodec/alpha \
         libavcodec/armv4l \
         libavcodec/bfin \
         libavcodec/i386 \
         libavcodec/mlib \
         libavcodec/ppc \
         libavcodec/sh4 \
         libavcodec/sparc \
         libavformat \
         libavutil \
         libpostproc \
         libswscale \
         tests \
         tools \
         vhook \
         "
    FILES="\
          Makefile \
          common.mak \
          doc/texi2pod.pl \
          libavcodec/Makefile \
          libavformat/Makefile \
          libavutil/Makefile \
          libpostproc/Makefile \
          libswscale/Makefile \
          "
    for dir in $DIRS ; do
            mkdir -p $dir
    done
    for f in $FILES ; do
        $ln_s "$source_path/$f" $f
    done
fi


# build pkg-config files
# FIXME: libdir and includedir are hardcoded and may differ from the real path.

pkgconfig_generate(){
name=$1
comment=$2
version=$3
libs=$4
requires=$5
include=$6
cat <<EOF >$name.pc
prefix=$PREFIX
exec_prefix=\${prefix}
libdir=\${exec_prefix}/lib
includedir=\${prefix}/include

Name: $name
Description: $comment
Version: $version
Requires: $requires
Conflicts:
Libs: -L\${libdir} $libs
Cflags: -I\${includedir} -I\${includedir}/$include
EOF
}

pkgconfig_generate_uninstalled(){
name=$1
shortname=${name#lib}
comment=$2
version=$3
libs=$4
requires=$5
cat <<EOF >$name-uninstalled.pc
prefix=
exec_prefix=
libdir=\${pcfiledir}/$name
includedir=\${pcfiledir}/$name

Name: $name
Description: $comment
Version: $version
Requires: $requires
Conflicts:
Libs: \${libdir}/${LIBPREF}${shortname}${LIBSUF} $libs
Cflags: -I\${includedir}
EOF
}

pkgconfig_generate libavutil "FFmpeg utility library" "$lavu_version" -lavutil "" ffmpeg
pkgconfig_generate_uninstalled libavutil "FFmpeg utility library" "$lavu_version"

pkgconfig_generate libavcodec "FFmpeg codec library" "$lavc_version" "-lavcodec $extralibs" "$pkg_requires libavutil = $lavu_version" ffmpeg
pkgconfig_generate_uninstalled libavcodec "FFmpeg codec library" "$lavc_version" "$extralibs" "$pkg_requires libavutil = $lavu_version"

pkgconfig_generate libavformat "FFmpeg container format library" "$lavf_version" "-lavformat $extralibs" "$pkg_requires libavcodec = $lavc_version" ffmpeg
pkgconfig_generate_uninstalled libavformat "FFmpeg container format library" "$lavf_version" "$extralibs" "$pkg_requires libavcodec = $lavc_version"

if enabled pp; then
  pkgconfig_generate libpostproc "FFmpeg post processing library" "$pp_version" -lpostproc "" postproc
  pkgconfig_generate_uninstalled libpostproc "FFmpeg post processing library" "$pp_version"
fi

if enabled swscaler; then
  pkgconfig_generate libswscale "FFmpeg image rescaling library" "$sws_version" -lswscale "libavutil = $lavu_version" ffmpeg
  pkgconfig_generate_uninstalled libswscale "FFmpeg image rescaling library" "$sws_version" "" "libavutil = $lavu_version"
else
  pkgconfig_generate libswscale "FFmpeg image rescaling library" "$sws_version" "" "$pkg_requires libavcodec = $lavc_version" ffmpeg
  pkgconfig_generate_uninstalled libswscale "FFmpeg image rescaling library" "$sws_version" "" "$pkg_requires libavcodec = $lavc_version"
  apply libswscale.pc sed s/^Libs:.*$/Libs:/
  apply libswscale-uninstalled.pc sed s/^Libs:.*$/Libs:/
fi
